<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
/**
 * telegram机器人api 作者qq 32579135
**/
class Api extends Controller
{
    
    public function index(){
        //设置连接根
        
        $id = $_GET['id'];
        $admin= Db::table('admin')->where('id',$id)->find();
        //  die;
        $token=$admin['token'];
        $url = "https://api.telegram.org/bot".$token."/";
       
        
        //获取反射信息
        $update = json_decode(file_get_contents('php://input'), true);
        // $myfile = fopen("video_check_log.txt", "w+") or die("Unable to open file!");
        // fwrite($myfile, json_encode($update));
        // fclose($myfile);
         
      $myfile = fopen("video_check_log.txt", "w+") or die("Unable to open file!");
                    fwrite($myfile,json_encode($update));
                    fclose($myfile); 
                      
        
        
        
        if(isset($update["callback_query"])){
            //按钮回调   
            $name = $update['callback_query']['message']['chat']['title'];
            $chat_id = $update['callback_query']['message']['chat']['id'];
            $text=$update['callback_query']['data'] ?? "凤雏";//获取用户消息
            
        }else if(isset($update['my_chat_member'])){
            //新成员 刚拉入
            //
             $name = $update['my_chat_member']['chat']['title'];
             $chat_id = $update['my_chat_member']['chat']['id'];
             $text=   "凤雏";//获取用户消息
             
             
        }else if(isset($update['edited_message'])){
            //群组
            
             $name = $update['edited_message']['chat']['title'];
             $chat_id = $update['edited_message']['chat']['id'];
             $text= $update['edited_message']['text'] ?? "凤雏";//获取用户消息
             
             
        }else if(isset($update['message'])){
            //私信
            $chat_id = $update['message']['chat']['id'];
            $name = $update['message']['from']['first_name'] ?? $update['message']['chat']['title'] ;
            $text=$update['message']['text'] ?? "凤雏";//获取用户消息
            if($update['message']['chat']['type'] == "group" || $update['message']['chat']['type'] == "supergroup"){
                
                $chat = Db::table('api_group')->where(['chat_id'=>$chat_id,'admin_id'=>$id])->select();
                 if(count($chat)==0){
                     $group['chat_title'] = $update['message']['chat']['title'];
                     $group['chat_id'] = $update['message']['chat']['id'];
                     $group['admin_id'] = $id;
                     Db::table('api_group')->insert($group);
                 }else{
                     Db::table('api_group')->where(['chat_id'=>$update['message']['chat']['id'],'admin_id'=>$id])->update(['chat_title'=>$update['message']['chat']['title']]);
                 }
                 
            }
            // 
            
        //  
        }else if(isset($update['channel_post'])){
        //     //群组
           
             $name =  $update['channel_post']['chat']['title'] ;
             $chat_id = $update['channel_post']['chat']['id'];
             $text= $update['channel_post']['text'] ?? "凤雏";//获取用户消息
               
               if(strpos($chat_id,'-') !== false){ 
                  $chat = Db::table('api_group')->where(['chat_id'=>$chat_id,'admin_id'=>$id])->select();
                 if(count($chat)==0){
                     
                     $group['chat_title'] = $update['channel_post']['chat']['title'] ?? "错误";
                     $group['chat_id'] = $update['channel_post']['chat']['id'] ?? "错误";
                     $group['admin_id'] = $id ?? 0;
                    try{
                    $articles = Db::table('api_group')->strict(false)->insert($group);
                    }
                    catch(\Exception $e){
                    // $this->error($e);
                   
                    }
                
                     
                 }else{
                     Db::table('api_group')->where(['chat_id'=>$update['channel_post']['chat']['id'],'admin_id'=>$id])
                     ->update(['chat_title'=>$update['channel_post']['chat']['title']]);
                 }
                }
          
         
             
        }else{
            //  $text = "凤雏";
            //  $name = "zzznl";
            //  $chat_id = '-1001321849310';
             return "无";
        }
        
      
        $data['text'] = $text ?? "凤雏";
        $data['name'] = $name ?? "zzznl";
        $data['chat_id'] = $chat_id ?? "1762378468";
        // $data['chat_id'] = -559355056;
        $data['time'] = time();
        
        // $tg_message=Db::table('tg_message')->insert($data);
       
        //获取数据库关键词
        $api=Db::table('api')
        ->alias('a')
        ->join('api_gid b','a.gid=b.gid','LEFT')
        ->where(['a.keywords'=>$data['text'],'a.admin_id'=>$id])
        ->field('a.gid as agid,a.*,b.*')
        ->find();
        
        
       
        
        // $api['text'] = str_replace("br", '\n',$api['text']);
        
        $btns = Db::table("btn")->where('admin_id',$id)->select();
        
        
        $inline_keyboard = [];
        $keyboard = [
            'inline_keyboard'=>[
                
                
                ]
            ];
        foreach ($btns as $btn){
            

            if($btn['type']==0){
                //内联
                $btn_data['text'] = $btn['text'];
                $btn_data['callback_data'] = $btn['cmd'];
                
                
            } else{
                $btn_data['text'] = $btn['text'];
                $btn_data['url'] = $btn['cmd'];
            }   
            
            array_push($inline_keyboard,$btn_data);
            $btn_data = [];
            if(count($inline_keyboard)>=4){
                array_push($keyboard['inline_keyboard'],$inline_keyboard);
                $inline_keyboard = [];
            }
            
        
        }
        
            array_push($keyboard['inline_keyboard'],$inline_keyboard);
            $response ="测试";
            
        
            $encodedKeyboard = json_encode($keyboard);
            // $parameters = 
            //         array(
            //             'chat_id' => $chat_id, 
            //             'text' => $response, 
            //             'reply_markup' => $encodedKeyboard
            //         );
            //  $parameters["method"] = "sendMessage";
                // echo json_encode($parameters);
        
        
        // $url = "https://api.telegram.org/bot1999732747:AAFcKcjdEv_Jv46g5sZsaMiIiXFLZ-gp29Y/";
        $url = $url.$api['api'].$api['text']."&chat_id=".$chat_id."&reply_markup=".$encodedKeyboard."&parse_mode=Markdown";
        // $myfile = fopen("video_check_log.txt", "a+") or die("Unable to open file!");
        // fwrite($myfile,$url);
        // fclose($myfile);  
        if($api){
        // file_get_contents($url . $api['api'] . $api['text'] ."&chat_id=" . $chat_id);  // parse_mode='Markdown' //"&parse_mode=Markdown"
       
            file_get_contents($url);
            exit;
        }
        
    }
    
    public function ceshi(){
        
        $data['text']=input('get.text');
                //获取数据库关键词
        $api=Db::table('api')
        ->alias('a')
        ->join('api_gid b','a.gid=b.gid','LEFT')
        ->where(array('keywords'=>$data['text']))
        ->field('a.gid as agid,a.*,b.*')
        ->find();
        dump($api);
    }
    
    public function corn(){
        
        $tg_message =  Db::table('tg_message')->count();
        if($tg_message>=10000){
            Db::table('tg_message')->delete(true);
        }
        $corn =  Db::table('corn')->where('type',1)->select();
        foreach ($corn as $key){
               
            //   dump($key);
               if(time() - $key['add_time'] >= $key['time']){
                   Db::table('corn')->where('id',$key['id'])->update(['add_time'=>time()]);
                   $this->corn_push($key['chat_id'],$key['chat_title'],$key['api_id'],$key['admin_id']);
               }
                
    
        }
        
    }
    
    public function corn_push($chat_id,$name,$api_id,$admin_id){
        //设置连接根
        
        

        
        $admin=Db::table('admin')->where(array('id'=>$admin_id))->find();
        $token=$admin['token'];
        $url = "https://api.telegram.org/bot".$token."/";
        
       
        $text = Db::table('api')->where(['id'=>$api_id,'admin_id'=>$admin_id])->value('keywords');
        // $name = "zzznl";
        $data['text']=$text ?? "凤雏";
        $data['name']=$name ?? "zzznl";
        $data['chat_id']=$chat_id ?? "1762378468";
        // $data['chat_id'] = -559355056;
        $data['time']=time();
        
        $tg_message=Db::table('tg_message')->insert($data);
        
      
        //获取数据库关键词
        $api=Db::table('api')
        ->alias('a')
        ->join('api_gid b','a.gid=b.gid','LEFT')
        ->where(['a.keywords'=>$data['text'],'a.admin_id'=>$admin_id])
        ->field('a.gid as agid,a.*,b.*')
        ->find();
        
        // $api['text'] = str_replace("br", '\n',$api['text']);
        
        $btns = Db::table("btn")->where('admin_id',$admin_id)->select();
        $inline_keyboard = [];
        $keyboard = [
            'inline_keyboard'=>[
                
                
                ]
            ];
        foreach ($btns as $btn){
            
            
            if($btn['type']==0){
                //内联
                $btn_data['text'] = $btn['text'];
                $btn_data['callback_data'] = $btn['cmd'];
                
                
            } else{
                $btn_data['text'] = $btn['text'];
                $btn_data['url'] = $btn['cmd'];
            }   
            
            array_push($inline_keyboard,$btn_data);
            $btn_data = [];
            if(count($inline_keyboard)>=4){
                array_push($keyboard['inline_keyboard'],$inline_keyboard);
                $inline_keyboard = [];
            }
            
        
        }
        array_push($keyboard['inline_keyboard'],$inline_keyboard);
            $response ="测试";
        
            $encodedKeyboard = json_encode($keyboard);
            // $parameters = 
            //         array(
            //             'chat_id' => $chat_id, 
            //             'text' => $response, 
            //             'reply_markup' => $encodedKeyboard
            //         );
            //  $parameters["method"] = "sendMessage";
                // echo json_encode($parameters);
        
        
        
        if($api){
        // file_get_contents($url . $api['api'] . $api['text'] ."&chat_id=" . $chat_id);  // parse_mode='Markdown' //"&parse_mode=Markdown"
            file_get_contents($url . $api['api'] . $api['text'] ."&chat_id=" . $chat_id."&reply_markup=" . $encodedKeyboard."&parse_mode=Markdown");
            exit;
        }
        
  
    }
}